package com.wang.controller;

import com.wang.config.MinIOInfo;
import com.wang.entity.UserContract;
import com.wang.entity.UserImage;
import com.wang.entity.UserInfo;
import com.wang.result.R;
import com.wang.service.UserContractService;
import com.wang.service.UserImageService;
import com.wang.service.UserInfoService;
import io.minio.*;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@CrossOrigin  // 解决跨域问题    前端和后端的域名（URL）不同，导致跨域问题，前端无法访问后端的接口
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinIOInfo minIOInfo;

    @Autowired
    private UserImageService userImageService;

    @Autowired
    private UserContractService userContractService;

    @GetMapping(value = "api/users")
    public R Users(){
        List<UserInfo> list = userInfoService.list();

        return R.OK(list);
    }
    @PostMapping(value = "api/users/image")//前端访问的请求方式为Post
    public R UsersImage(MultipartFile file,@RequestParam("id") Integer id) throws Exception {
        //获取文件后缀名
        String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        //拼接新文件名
        String object = id + subfix;
        ObjectWriteResponse myfile = minioClient.putObject(PutObjectArgs.builder()
                .bucket(minIOInfo.getBucketName())
                .object(object)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());

        System.out.println("图片上传成功！");

        UserImage userImage = new UserImage();
        userImage.setUid(id);
        userImage.setBucket(minIOInfo.getBucketName());
        userImage.setObject(object);
        userImageService.saveOrUpdateUserImage(userImage);
        return R.OK();
    }

    @PostMapping(value = "api/users/contract")//前端访问的请求方式为Post
    public R UsersContract(MultipartFile file,@RequestParam("id") Integer id) throws Exception{
        //获取文件后缀名
        String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        //拼接新文件名
        String object = id + subfix;
        ObjectWriteResponse myfile = minioClient.putObject(PutObjectArgs.builder()
                .bucket(minIOInfo.getBucketName())
                .object(object)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());
        System.out.println("合同上传成功！");

        UserContract userContract = new UserContract();
        userContract.setUid(id);
        userContract.setBucket(minIOInfo.getBucketName());
        userContract.setObject("contract.pdf");
        userContractService.saveOrUpdateUserContract(userContract);
        return R.OK();
    }

    // 根据id查询用户信息   进行链表查询（查出用户表信息、合同表信息、头像表信息）
    @GetMapping(value = "api/users/{id}")
    public R getUserInfo(@PathVariable("id") Integer id){
        UserInfo userInfo = userInfoService.getUserById(id);
        return R.OK(userInfo);
    }


    // 修改用户信息
    @PutMapping(value = "api/user")
    public R updateUser(UserInfo userInfo){
        boolean b = userInfoService.updateById(userInfo);
        return b ? R.OK() : R.FALSE();
    }

    //合同的下载
    @GetMapping(value = "api/download/{id}")
    public void download(@PathVariable("id") Integer id, HttpServletResponse response)throws Exception{
        //一对多关联查询，查找合同表中的minio的object和bucket
        UserInfo userById = userInfoService.getUserById(id);
        String object = userById.getUserContractDO().getObject();
        String bucket = userById.getUserContractDO().getBucket();

        //要想让浏览器弹出下载框，你后端要设置一下响应头信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(object, StandardCharsets.UTF_8));


        GetObjectResponse file = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucket)
                .object(object)
                .build());

        // 把文件内容写到response的输出流中
        file.transferTo(response.getOutputStream());
    }

    @DeleteMapping(value = "api/delete/{id}")
    public R deleteUser(@PathVariable("id") Integer id) throws Exception{
        boolean b = userInfoService.deleteUserById(id);
        return b ? R.OK() : R.FALSE();
    }
}
